<!--首页轮播图-->
<template>
  <swiper ref="swiper" :key="refreshKey" :options="swiperOption" v-if="bannerList.length>0">
    <swiper-slide  class="swiper-slide" v-for="(item,index) in bannerList" :key="index">
      <div  class="slide-img">
        <div v-if="getToday(item)" class="today">{{getTimeStr(Date.now())}}</div>
        <img v-if="getToday(item)" src="../../../static/images/dangjian/home/today-history.jpg"/>
        <img v-else="" :src="getImgUrl(item,true)"/>
      </div>
      <div class="banner-text">{{item.title}}{{getToday(item) ? '（'+getTimeStr1(Date.now())+'）':''}}</div>
      <div class="banner-text">{{item.title}}</div>
    </swiper-slide>

    <!-- 分页器 -->
    <!--<div class="swiper-pagination" slot="pagination"></div>-->
    <!-- 左右箭头 -->
  </swiper>

<!--  <slider :pages="pages" :sliderinit="sliderinit">
    &lt;!&ndash; slot  &ndash;&gt;
  </slider>-->
</template>

<script>
  /**
   * 首页banner 分为活动的及固定的
   * 活动的通过接口获取，固定的与后台约定栏目ID主动获取
   */
  import moment from 'moment'
  import 'swiper/dist/css/swiper.css'
  import StorageKeys from '@/common/const/StorageKeys'
  import _ from 'lodash'
  import {mapState} from 'vuex'
  let vm = null
  export default {
    name: 'banner',
    data () {
      return {
        bannerList: [],
        pages: [],
        refreshKey: '',
        sliderinit: {
          currentPage: 0,//当前页码
          thresholdDistance: 500,//滑动判定距离
          thresholdTime: 100,//滑动判定时间
          autoplay:1000,//自动滚动[ms]
          loop:true,//循环滚动
          direction:'vertical',//方向设置，垂直滚动
          infinite:1,//无限滚动前后遍历数
          slidesToScroll:1,//每次滑动项数
        },
        swiperOption: {
          slidesPerView: 1,
          spaceBetween: 0,
          loopFillGroupWithBlank: true,
          //显示分页
          pagination: {
            el: '.swiper-pagination'
          },
          //设置点击箭头
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev'
          },
          loop: true,
          //自动轮播
          autoplay: {
            delay: 2000,
            //当用户滑动图片后继续自动轮播
            disableOnInteraction: false,
            autopalyDisableOnInteraction: false,
            stopOnLastSlide: false
          },
          on: {
            click () {
              let currentIndex = this.realIndex
              vm.go(vm.bannerList[currentIndex])
            }
          }
        }
      }
    },
    created () {
      vm = this
      this.$nextTick(() => {
        this.init()
      })
    },
    activated () {
      this.$nextTick(() => {
        if (vm.$refs.swiper) {
          /*防止轮播异常*/
          vm.$refs.swiper.swiper.destroy()
          /*确保轮播正常进行*/
          vm.$refs.swiper.mountInstance()
        }
      })
    },
    computed: {
      ...mapState([
        'BANNER_AND_VIDEO',
        'RED_CLOUD_UNION'
      ])
    },
    methods: {
      init () {
        this.bannerList = this.getDataByStorageKey(StorageKeys.HOME_BANNER) || this.bannerList
        if (this.isNeedFetchData(StorageKeys.HOME_BANNER) || this.tools.isNoData(this.bannerList)) {
          this.bannerQuery()
        }
      },
      go (item) {
        // 需要详情数据的情况
        if (item.url.indexOf('http') < 0) {
          // item.url = 'videoDetail?id=d9d3f469eb2ea1a311b1c60eaab1406b&isVideo=true'
          // item.url = 'longVideoList?id=15c9e36223ec43f08a178ec3473e9b08&pageTitle=课件点播'
            /*let id= item.url.substring(item.url.indexOf('id=')+3,item.url.indexOf('&pageTitle'))
            let pageTitle= item.url.substring(item.url.indexOf('pageTitle=')+10) || '课件点播'*/
          if (item.url.indexOf('longVideoList') !=-1) {//红云视听列表
            this.$router.push({path: item.url })
            // this.$router.push({name: 'longVideoList',query:{id:id,pageTitle:pageTitle}})
            return false
          }
          if (item.url.indexOf('videoDetail') !=-1) {//红云视听详情
            let id= item.url.substring(item.url.indexOf('id=')+3,item.url.indexOf('&'))
            let isVideo= item.url.substring(item.url.lastIndexOf('=')+1)
              this.fetchService.contentPageDetail(id).then( (res)=> {
                if (res.code == 0) {
                  if(isVideo =='true'){
                    this.$store.state.isVideo = true
                  }else{
                    this.$store.state.isVideo = false
                  }
                  this.$store.state.videoDetail = res.data.newsContent
                  this.$store.state.newsDetail = res.data.newsContent
                  this.$router.push({name: 'videoDetail',  query: {id: id, zhuanji: 1}})
                }
              })
            return false
          }
          // 已经有详情数据
          if (item.async_data) {
            this.jumpByDetail(item.async_data, item)
            return false
          }
          // 主题活动入口
          if (item.url.indexOf('themeActivity')!=-1) {
            this.$router.push({name:'themeActivity',query:{index: 0}})
            return false
          }
          return this.fetchService.contentPageDetail(item.url).then(res => {
            if (res.code === 0) {
              console.log('go', item)
              let data = res.data
              item.async_data = data
              this.jumpByDetail(data, item)
            } else {
              this.tools.tip('请重试')
            }
          })
        }
        if(this.getToday(item)){
          return this.fetchService.todayPageDetail(item.url).then(res => {
            if (res.code === 0) {
              console.log('go', item)
              let data = res.data
              item.async_data = data
              this.jumpByDetail(data, item)
            } else {
              this.tools.tip('请重试')
            }
          })
        }
        let url = item.url
        if (url.indexOf('?') >= 0) {
          url = url + '&access_token=' + this.tools.getToken()
        } else {
          url = url + '?access_token=' + this.tools.getToken()
        }
        console.log(url)
        if (window.android && window.android.openUrlAdapt) {
          window.android.openUrlAdapt(url)
        }
      },
      /*需要具体的详情数据才能跳转
      * data 为详情数据
      * item 为列表项数据
      */
      jumpByDetail (data, item) {
        if (data.newsContent.channelId === '1deda3e0e5ff41c99706f69544a41927') {
          return this.$router.push({name: 'todayDetail', query: {channelId: item.channelId, channelName: '党史上的今天'}})
        }
        if (item._channelType === '1') {
          return this.$router.push({name: 'todayDetail', query: {channelId: item.channelId, channelName: '党史上的今天'}})
        } else if (item._channelType === '0') {
          return this.$router.push({name: 'fixDetail', query: {channelId: item.channelId, channelName: item.channelName, type: item.type}})
        }
        this.$store.state.newsDetail = item
        if (item.sfwblj === '0') {
          this.$router.push({name: 'redCloudNewsDetail', params: {id: item.url,channelId: item.channelId, title: '首页'}})
        } else {
          if (window.android && window.android.openUrlAdapt) {
            let url = item.url
            if (url.indexOf('?') >= 0) {
              url = url + '&access_token=' + this.tools.getToken()
            } else {
              url = url + '?access_token=' + this.tools.getToken()
            }
            window.android.openUrlAdapt(url)
          }
        }
      },
      getImgUrl (item) {
        if(this.tools.indexOfHttp(item.titlePicUrl)){
          return item.titlePicUrl
        }
        return this.tools.getImgUrl(item.titlePic)
      },
      /*获取详情数据*/
      fetchDetail (list) {
        let me = this
        list.map((v, index) => {
          (function (item, index) {
            if (item.url.indexOf('http') < 0) {
              me.fetchService.contentPageDetail(item.url).then(res => {
                if (res.code === 0) {
                  me.bannerList[index]['async_data'] = res.data
                  me.$localStorage.set(StorageKeys.HOME_BANNER, me.bannerList)
                }
              })
            }
          })(v, index)
        })
      },
      /*获取缓存数据*/
      getDataByStorageKey (key) {
        let _list = this.$localStorage.get(key)
        if (_list && (Array.isArray(_list) && _list.length > 0)) {
          return _list
        }
        return false
      },
      /*判断是否需要拉取数据*/
      isNeedFetchData (key) {
        if (!this.getDataByStorageKey(key) || (Date.now() - this.$localStorage.get(StorageKeys.HOME_FETCH_TIME)) > 3600 * 1000) {
          return true
        }
        return false
      },
      bannerQuery () {
//        if (!this.isNeedFetchData(StorageKeys.HOME_BANNER)) {
//          return
//        }
        let params = {
          "limit": 40,
          "page": 1
        }
        let me = this
        this.fetchService.bannerQuery(params).then(res => {
          if (res.code !== 0) {
            return this.tools.tip(res.message)
          }
          if (res.data.length === 0) {
            return
          }
          this.bannerList = res.data
          this.fetchDetail(this.bannerList)
          me.$localStorage.set(StorageKeys.HOME_BANNER, me.bannerList)
          /*this.bannerList.forEach(v => {
            let data = {
                item: v,
                title: '',
                style:{
                  background:`url(${this.getImgUrl(v.titlePic)})`
                }
              }
            this.pages.push(data)
          })*/
        })
      },
      fixBanner () {
        /**
         * 首页轮播新增的栏目ID
         1deda3e0e5ff41c99706f69544a41927 党史上的今天
         11949660762540c8bcaf5ac2e1a05316 时政要闻
         6a0196c897a149848ebe7d5b1eb8238e 关注
         7ec897fe76a940fe83e12234ca3193fa 快讯
         */
        /**
         * channelType:1 代表党史上的今天
         *  1:时政要闻;2:关注;3:快讯
         */
        [
          {channelId: '1deda3e0e5ff41c99706f69544a41927', type: '0', _channelType: '1', channelName: '党史上的今天'},
          {channelId: '11949660762540c8bcaf5ac2e1a05316', type: '1', _channelType: '0', channelName: '时政要闻'},
          {channelId: '6a0196c897a149848ebe7d5b1eb8238e', type: '2', _channelType: '0', channelName: '关注'},
          {channelId: '7ec897fe76a940fe83e12234ca3193fa', type: '3', _channelType: '0', channelName: '快讯'},
        ].forEach(v => {
          this.getChannel(v)
        })
      },
      getChannel (data) {
        this.fetchService.channel(data.channelId).then(res => {
          if (res.code !== 0) {
            return
          }
          res.data.titlePic = res.data.pic || '4459504994cd4d04991f570b813cf3d0'
          let tempData = _.extend({}, data, res.data)
          this.bannerList.push(tempData)
          console.log(this.bannerList)
        })
      },
      getTimeStr (time) {
        return moment(time).format('M月DD日')
      },
      getTimeStr1 (time) {
        return moment(time).format('MM月DD日')
      },
      getToday (item){
        let str = '/cms/news/content/history'
        // let str = 'false'
        if (item.url.toLowerCase().indexOf(str.toLowerCase()) !=-1 ) {
        // if (true ) {
          return true
        }
        return false
      },

    },
    watch: {
      BANNER_AND_VIDEO (newVal) {
        if (newVal) {
          this.bannerQuery()
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .banner-text {
    font-size:14PX;
    overflow: hidden;
    width:70%;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding:10px 15px;
  }
  .today{
    position: absolute;
    top: 64%;
    font-size: 0.6rem;
    width: 100%;
    text-align: center;
    color: #F1EEF7;
    text-shadow: 0.06667rem 0.02667rem 0.08rem #000;
    font-family: \5B8B\4F53;
    font-weight: bold;
    text-shadow: 1px 1px 2px #000, -1px 1px 2px #000, 1px -1px 2px #000, -1px -1px 2px #000;
  }
</style>
